package com.sun.dao.user;

import com.mysql.jdbc.StringUtils;
import com.sun.dao.BaseDao;
import com.sun.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Sun
 * @Date 2020/4/25 10:46
 * @Version 1.0
 */
public class UserDaoImpl implements UserDao {
    //得到要登陆的用户
    public User getLoginUser(Connection connection, String userCode, String password) throws SQLException {

        PreparedStatement pre = null;
        ResultSet rs = null;
        User user = null;

        if (connection != null) {
            Object params[] = {userCode, password};
            String sql = "select * from smbms_user where userCode=? and userPassword=?";
            rs = BaseDao.execute(connection, pre, rs, sql, params);

            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
            }
            BaseDao.closeResource(null, pre, rs);
        }
        return user;
    }

    //修改密码
    public int updatepwd(Connection connection, int id, String password) throws SQLException {
        PreparedStatement pre = null;
        int affectRows = 0;

        if (connection != null) {
            Object[] params = {password, id};
            String sql = "update smbms_user set userPassword=? where id=?";
            affectRows = BaseDao.execute(connection, pre, sql, params);
            BaseDao.closeResource(null, pre, null);
        }
        return affectRows;
    }

    //根据输入的用户名或角色查询用户总数
    public int getUserCount(Connection connection, String userName, int userRole) throws SQLException {
        PreparedStatement pre = null;
        ResultSet rs = null;
        int count = 0;

        if(connection!=null){
            StringBuffer sql =  new StringBuffer();
            ArrayList<Object> list = new ArrayList<Object>();// 存放参数

            sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole=r.id");

            if(!StringUtils.isNullOrEmpty(userName)){
                sql.append(" and u.userName like ?");
                list.add("%"+userName+"%");// index:从0开始
            }

            if(userRole>0){
                sql.append(" and u.userRole like ? ");
                list.add(userRole);
            }

            // 将list转换成数组
            Object[] params = list.toArray();

            System.out.println("UserDaoImpl->getUserCount()->"+sql.toString());

            rs = BaseDao.execute(connection, pre, rs, sql.toString(), params);

            if(rs.next()){
                count = rs.getInt("count");//获取查询的数量
            }

            BaseDao.closeResource(null, pre, rs);
        }

        return count;

    }

    //分页查询用户列表
    public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws SQLException {
        PreparedStatement pre = null;
        ResultSet rs = null;
        ArrayList<User> userList = new ArrayList<User>();

        if(connection!=null){

            StringBuffer sql = new StringBuffer();
            ArrayList<Object> list = new ArrayList<Object>();

            sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole=r.id");

            if(!StringUtils.isNullOrEmpty(userName)){
                sql.append(" and u.userName like ?");
                list.add("%"+userName+"%");// index:从0开始
            }

            if(userRole>0){
                sql.append(" and u.userRole like ? ");
                list.add(userRole);
            }

            sql.append(" order by creationDate DESC limit ?,? ");//分页查询
            currentPageNo = (currentPageNo-1)*pageSize;
            list.add(currentPageNo);//当前页码，每一页开始的行数编号=（当前页码-1）*页面容量
            list.add(pageSize);//每一页显示用户列表的容量

            Object[] params = list.toArray();

            System.out.println("getUserList()->"+sql.toString());

            rs = BaseDao.execute(connection, pre, rs, sql.toString(), params);

            while (rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setUserRole(rs.getInt("userRole"));
                user.setUserRoleName(rs.getString("userRoleName"));
                userList.add(user);
            }

            BaseDao.closeResource(null, pre, rs);
        }

        return userList;
    }

    public int addUser(Connection connection,User user) {
        PreparedStatement pre = null;
        int affectRows = 0 ;

        if(connection!=null){
            String sql = "insert smbms_user(id,userName,userPassword,gender,birthday,phone,address" +
                    ",userRole,modifyBy,modifyDate) values (?,?,?,?,?,?,?,?,?,?)";

            Object[] params = {user.getId(),user.getUserName(),user.getUserPassword(),user.getGender(),
            user.getBirthday(),user.getAddress(),user.getUserRole(),user.getModifyBy(),user.getModifyDate()};

            BaseDao.closeResource(null, pre, null);
            try {
                affectRows = BaseDao.execute(connection, pre, sql, params);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return affectRows;
    }

}
